package org.dyndns.opendemogroup.optimizer.operations;

import java.util.Random;

import org.dyndns.opendemogroup.optimizer.IOperation;
import org.dyndns.opendemogroup.optimizer.IOptimizationProblem;
import org.dyndns.opendemogroup.optimizer.Member;

/**
 * Will randomly flip bits in copies of the parents.
 */
public class BitFlipperMutator implements IOperation
{

	private int mutationProbability;

	public BitFlipperMutator ( int mutationProbability )
	{
		this.mutationProbability = mutationProbability;
	}

	/**
	 * @see IOperation#perform(java.util.Random, IOptimizationProblem, Member,
	 *      Member, Member, Member)
	 */
	public void perform ( Random randomSource, IOptimizationProblem problem,
			Member parentOne, Member parentTwo, Member childOne, Member childTwo )
	{
		int memberSize = parentOne.getMemberSize ( );
		// perform mutations
		mutate ( randomSource, parentOne, childOne, memberSize );
		mutate ( randomSource, parentTwo, childTwo, memberSize );
	}

	void mutate ( Random randomSource, Member parent, Member child,
			int memberSize )
	{
		child.copyFrom ( parent, 0, memberSize - 1 );
		for ( int j = 0; j < memberSize; j++ )
		{
			int shouldMutate = randomSource.nextInt ( mutationProbability );
			if ( shouldMutate < 1 )
			{
				child.genome[j] = ( 1 == child.genome[j] ) ? 0 : 1;
			}
		}
	}

}
